//
//  User.swift
//  ShareCar
//
//  Created by lishuai on 2018/6/21.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import Foundation

//登录模型
class Login: NSObject, NSCoding, Codable {
    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.token, forKey: "token")
        aCoder.encode(self.certFlag, forKey: "certFlag")
        aCoder.encode(self.userId, forKey: "userId")
        aCoder.encode(self.username, forKey: "username")
        aCoder.encode(self.nickname, forKey: "nickname")
        aCoder.encode(self.sex, forKey: "sex")
        aCoder.encode(self.avatarPath, forKey: "avatarPath")
        aCoder.encode(self.chengValue, forKey: "chengValue")
        aCoder.encode(self.telephone, forKey: "telephone")
        aCoder.encode(self.isDeposit, forKey: "isDeposit")
        aCoder.encode(self.memberType, forKey: "memberType")
        aCoder.encode(self.isDayDeposit, forKey: "isDayDeposit")
        aCoder.encode(self.bindFlag, forKey: "bindFlag")
        aCoder.encode(self.certStep, forKey: "certStep")
    }
    
    required init?(coder aDecoder: NSCoder) {
        self.token = aDecoder.decodeObject(forKey: "token") as! String
        self.certFlag = Int(aDecoder.decodeInt64(forKey: "certFlag"))
        self.userId = aDecoder.decodeObject(forKey: "userId") as! String
        self.username = aDecoder.decodeObject(forKey: "username") as! String
        self.nickname = aDecoder.decodeObject(forKey: "nickname") as! String
        self.sex = Int(aDecoder.decodeInt64(forKey: "sex"))
        self.avatarPath = aDecoder.decodeObject(forKey: "avatarPath") as! String
        self.chengValue = Int(aDecoder.decodeInt64(forKey: "chengValue"))
        self.telephone = aDecoder.decodeObject(forKey: "telephone") as! String
        self.isDeposit = Int(aDecoder.decodeInt64(forKey: "isDeposit"))
        self.memberType = Int(aDecoder.decodeInt64(forKey: "memberType"))
        self.isDayDeposit = Int(aDecoder.decodeInt64(forKey: "isDayDeposit"))
        self.bindFlag = Int(aDecoder.decodeInt64(forKey: "bindFlag"))
        self.certStep = Int(aDecoder.decodeInt64(forKey: "certStep"))
    }
    var token: String
    var certFlag: Int
    var userId: String
    var username: String
    var nickname = ""
    var sex: Int
    var avatarPath = ""
    var chengValue: Int
    var telephone: String
    var isDeposit: Int
    var memberType: Int
    var isDayDeposit: Int
    var bindFlag: Int
    var certStep: Int
    
    enum CodingKeys : String, CodingKey {
        case token
        case certFlag = "cert_flag"
        case userId =  "user_id"
        case username = "user_name"
        case isDeposit = "is_deposit"
        case nickname
        case sex
        case avatarPath = "avatar_path"
        case chengValue = "cheng_value"
        case telephone
        case memberType = "member_type"
        case isDayDeposit = "is_day_deposit"
        case bindFlag = "bind_flag"
        case certStep = "cert_step"
    }
}

struct User: Codable {
    
    enum Status: Int, Codable {
        case reserve = 1
        case cancel = 2
        case using = 3
        case confrimReturnCar = 4
        case confrimPay = 5
        case finished = 6
    }
    enum ForceStatus: Int, Codable {
        case unForce = 1
        case forcing = 2
        case forceed = 3
    }
    
    enum DebtStatus: Int, Codable {
        case undebt = 1
        case debted = 2
        case judicial = 3
    }

    //我的行程  模型
    struct TripList:Codable {
        let list : [TripInfo]
        //一个行程订单模型
        struct TripInfo: Codable{
            let orderId : String
            let plateNumber : String
            let carTypeName : String
            let imagePath : String
            let drivingDistance : Int
            let drivingDuration : Int
            let status : User.Status
            let created : String
            let payStatus : User.PayStatus
            let debtFlag : User.DebtStatus
            let forceFlag: ForceStatus
            let ordersn: String
            let beginTime: Int?
            let endTime: Int?
            let orderType: OrderType?
            let isNeedPay: User.IsNeedPay?
            
            enum CodingKeys: String, CodingKey {
                case orderId = "order_id"
                case plateNumber = "plate_number"
                case carTypeName = "car_type_name"
                case imagePath = "image_path"
                case drivingDistance = "driving_distance"
                case drivingDuration = "driving_duration"
                case status = "status"
                case created = "created"
                case payStatus = "pay_status"
                case debtFlag = "debt_flag"
                case forceFlag = "force_flag"
                case ordersn = "order_sn"
                case beginTime = "begin_time"
                case endTime = "end_time"
                case orderType = "order_type"
                case isNeedPay = "is_need_pay"
            }
        }
    }
    
    //获取押金的模型
    struct Deposit : Codable{
        let basicDeposit : String
        let payableDeposit : String
        let payeddeposit: String
        let depositStatus: Int
        let isBoundCard: Int?
        
        enum CodingKeys : String, CodingKey {
            case basicDeposit = "basic_deposit"
            case payableDeposit = "payable_deposit"
            case payeddeposit = "paid_deposit"
            case depositStatus = "deposit_status"
            case isBoundCard = "isBoundCard"
        }
    }
}

extension User {
    //用户信息
    static func info() -> Login? {
        return UserDefaults.standard.getCustomObject(forKey: kUserInfo) as? Login
    }
    
    //是否登录
    static func isLogin() -> Bool {
        return User.info() != nil
    }
    
    //是否注册
    static func isAuthentication() -> Bool {
        guard let user = User.info() else {
            return false
        }
        
        return user.certFlag == 2
    }
    
    //是否缴纳押金
    static func isPaydeposit() -> Bool {
        guard let user = User.info() else {
            return false
        }
        
        return user.isDeposit == 2
    }
    
    //是否绑定信用卡
    static func isBoundCard() -> Bool {
        guard let user = User.info() else {
            return false
        }
        return user.bindFlag == 2
    }
    
    //是否缴纳日租金
    static func isPayDaydeposit() -> Bool {
        guard let user = User.info() else {
            return false
        }
        return user.isDayDeposit == 2
    }
    
    //用户类型
    static func memberType() -> Int {
        guard let user = User.info() else {
            return 1
        }
        return user.memberType
    }
    
    //保存用户信息
    static func saveUserInfo(_ object: NSCoding) {
        UserDefaults.standard.saveCustomObject(customObject: object, key: kUserInfo)
    }
    
    //登录
    static func login(telephone: String,
                      smsCode: String,
                      success: @escaping () -> (),
                      failure: @escaping (Message) -> ()) {
        var parameters = ["telephone": telephone, "sms_code": smsCode]
        
        let def = UserDefaults.standard
        
        if def.string(forKey: "tuia_id") != nil {
            def.removeObject(forKey: "tuia_id")
            parameters["ad_source"] = "tuia"
        }
        
        Base<Login>.request(URIString: "user/login", parameters: parameters, success: { data in
            if let login = data {
                User.saveUserInfo(login)
                success()
            } else {
                failure(Message(code: -10000, msg: "登录失败"))
            }
        }) { error, data in
            failure(error)
        }
    }
    
    //退出登录
    static func logout() {
        UserDefaults.standard.removeObject(forKey: kUserInfo)
        UserDefaults.standard.removeObject(forKey: "com.jz.get_user_progress_order")
        UserDefaults.standard.removeObject(forKey: "com.jz.get_progress_order_detail")
    }
    
    struct MobileCode: Codable {
        let smsCode: String
        enum CodingKeys : String, CodingKey {
            case smsCode = "sms_code"
        }
    }
    
    //用户获取验证码
    static func makeMessageCode(telephone:String,
                                time:String,
                                signature:String,
                                sendCount: Int,
                                success: @escaping () ->(),
                                failure: @escaping (Message) -> ()) {
        
        let parameters: [String : Any] = ["telephone": telephone,
                                          "time": time,
                                          "signature": signature,
                                          "send_count": sendCount]
        
        Base<MobileCode>.request(URIString: "user/get_verification_code", parameters: parameters, success: { data in
            p(data?.smsCode)
            success()
        }) { (message, codeData) in
            failure(message)
        }
    }
    
    struct UserInfo :Codable {
        let telephone : String
        let user_name : String
        let identify_card: String
        let nickname : String
        let sex : Int
        let avatar_path : String
        let cert_flag : Int
        let cheng_value : Int
        let is_deposit : Int
        let money : String
        let mi_money : String
        let coupon_count : Int
        let daily_deposit: String
        let bind_flag: Int
        let day_coupon_count: Int
        let cert_step: Int
    }
    
    //获取用户信息
    static func fetchUserInfo(success: @escaping (UserInfo?) -> (),
                              failure: @escaping (Message) -> ()) {
        Base<UserInfo>.request(URIString: "user/get_user_info", success: { (data) in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    
    struct Reasons: Codable {
        let fault_reason_list: [Reason]
        
        struct Reason: Codable {
            let faultReasonId: String
            let reasonName: String
            
            enum CodingKeys: String, CodingKey {
                case faultReasonId = "fault_reason_id"
                case reasonName = "reason_name"
            }
        }
    }
    
    //获取我的行程列表
    static func tripListForme(page: Int,
                              page_size: Int,
                              kind: OrderType,
                              success: @escaping ([TripList.TripInfo]?) -> (),
                              failure: @escaping (Message) -> ()) {
        
        let parameters = ["page": page,
            "page_size": page_size,
            "order_type":kind.rawValue] as [String : Any]
        
        Base<TripList>.request(URIString: "user/my_order", parameters: parameters, success: { data in
            success(data?.list)
        }) { error, data in
            failure(error)
        }
    }

    //获取故障上报原因
    static func declareReason(success: @escaping ([Reasons.Reason]?) -> (),
                              failure: @escaping (Message) -> ()) {
        Base<Reasons>.request(URIString: "user/get_fault_reason_list", success: { data in
            success(data?.fault_reason_list)
        }) { error, data in
            failure(error)
        }
    }
    
    //上报故障
    static func commitReason(reasons: [String],
                             plateNumber: String,
                             otherReason: String?,
                             imagePath: [String]?,
                             success: @escaping () -> (),
                              failure: @escaping (Message) -> ()) {

        let paramter: [String: Any] = [
            "fault_reason":reasons,
            "plate_number":plateNumber,
            "other_reason":otherReason ?? "",
            "image_path":imagePath ?? []
        ]
        
        Base<String>.request(URIString: "user/add_car_fault", parameters:paramter, success: { data in
            success()
        }) { (message, temp) in
            failure(message)
        }
    }
    
    struct addressInfo: Codable {
        let list: [String]
    }
    
    //获取故障上报原因
    static func chooseAdresscity(success: @escaping (addressInfo?) -> (),
                              failure: @escaping (Message) -> ()) {
        Base<addressInfo>.request(URIString: "user/get_car_first_name", success: { data in
            success(data)
        }) { error, data in
            failure(error)
        }
    }

    //更新用户信息
    static func updateuserInfo(photoAdress: String,
                               success: @escaping (UserInfo?) -> (),
                              failure: @escaping (Message) -> ()) {
        
        Base<UserInfo>.request(URIString: "user/alter_info", parameters: ["avatar_path":photoAdress], success: { data in
            success(data)
        }) { (error, data) in
            failure(error)
        }
    }
    
    struct Certification: Codable {
        
        /// 驾驶证档案编号
        let drivingLicenseFn: String
        
        enum CodingKeys : String, CodingKey {
            case drivingLicenseFn = "driving_license_fn"
        }
    }
    
    //实名认证身份证
    static func AuthenticationIDCard(idcardFrontImg:String,
                                     idcardBackImg:String,
                                     idcardHandImg:String,
                                     realName:String,
                                     idcardNumber:String,
                                     success: @escaping (Certification?) -> (),
                                     failure: @escaping (Message) -> ()) {
        let parameters = [
            "idcard_front_img": idcardFrontImg,
            "idcard_back_img": idcardBackImg,
            "idcard_hand_img": idcardHandImg,
            "real_name": realName,
            "idcard_number": idcardNumber
        ]
        
        Base<Certification>.request(URIString: "user/v2.6/certification", parameters: parameters, success: { data in
            success(data)
        }) { (message, code) in
            failure(message)
        }
    }
    
    //实名认证驾照
    static func AuthenticationDrivingLicense(drivingLicenseImg:String,
                                             drivingLicensePageImg:String,
                                             drivingLicenseFn:String,
                                             success: @escaping () -> (),
                                             failure: @escaping (Message) -> ()) {
        let parameters = [
            "driving_license_img": drivingLicenseImg,
            "driving_license_page_img": drivingLicensePageImg,
            "driving_license_fn": drivingLicenseFn
        ]
        
        Base<Certification>.request(URIString: "user/v2.6/certification", parameters: parameters, success: { data in
            success()
        }) { (message, code) in
            failure(message)
        }
    }
    
    //获取押金
    static func deposit(
        status: Int,
        success: @escaping (Deposit?) -> (),
        failure: @escaping (Message) -> ()) {
        
        let paramter = ["deposit_type":status]
        Base<Deposit>.request(URIString: "user/get_deposit", parameters: paramter, success: { data in
            success(data)
        }) { (error, data) in
            failure(error)
        }
    }

    struct OrderPay: Codable {
        let appid : String
        let partnerid : String
        let prepayid : String
        let timestamp : String
        let noncestr : String
        let package : String
        let sign : String
    }
    
    //支付字符串
    struct PayInfo: Codable{
        let pay_str : String
    }
    
    //缴纳押金
    static func payDeposit(deposit: Float,
                           payWay: Int,
                           type: Int,
                           success: @escaping (PayInfo?) -> (),
                           failure: @escaping (Message) -> ()) {
        
        let paramter = ["deposit":deposit,
                        "payment":payWay,
                        "deposit_type":type] as [String : Any]
        
        Base<PayInfo>.request(URIString: "user/pay_deposit", parameters: paramter, success: { data in
            success(data)
        }) { (error, data) in
            failure(error)
        }
    }
    
    struct MemberInfo: Codable {
        
        let memberInfo: PayCardInfo?
        let monthMember: CardType
        let yearMember: CardType
        
        struct CardType: Codable {
            
            let expiryDays: Int
            let memberType: Int
            let originalPrice: Int
            let realPrice: Int
            let brief: String
            let balanceFlag: Int
            
            enum CodingKeys: String, CodingKey {
                case expiryDays = "expiry_days"
                case memberType = "member_type"
                case originalPrice = "original_price"
                case realPrice = "real_price"
                case brief = "brief"
                case balanceFlag = "balance_flag"
            }
        }
        
        struct PayCardInfo: Codable {
            let memberType: Int
            let expiryDate: String
            let discount: String
            
            enum CodingKeys: String, CodingKey {
                case expiryDate = "expiry_date"
                case memberType = "member_type"
                case discount = "discount"
            }
        }

        enum CodingKeys: String, CodingKey {
            case memberInfo = "member_info"
            case monthMember = "month_member"
            case yearMember = "year_member"
        }
    }
    
    //获取我的付费会员
    static func getUsermoneyInfo(
        success: @escaping (MemberInfo?) -> (),
        failure: @escaping (Message) -> ()) {
        
        Base<MemberInfo>.request(URIString: "user/get_member_type", success: { data in
            p(data)
            p(data?.memberInfo)
            success(data)
        }) { (message, cardInfo) in
            failure(message)
        }
    }
    
    //购买会员卡
    static func PayMonthandYearCard(
        member_type:Int,
        payment:Int,
        success: @escaping (PayInfo?) -> (),
        failure: @escaping (Message) -> ()) {
        
        Base<PayInfo>.request(URIString: "user/buy_member", parameters: ["member_type":member_type,"payment":payment], success: { (data) in
            success(data)
        }) { (mess, info) in
            failure(mess)
        }
    }
    
    //我的行程  模型
    struct CouponList: Codable {
        let list : [Coupon]
        //一个优惠券模型
        struct Coupon: Codable{
            let couponName : String
            let superpositionFlag : Int
            let brief : String
            let eventType : Int
            let expireTime : String
            let useFlag : Int
            
            enum CodingKeys: String, CodingKey {
                case couponName = "coupon_name"
                case superpositionFlag = "superposition_flag"
                case brief = "brief"
                case eventType = "event_type"
                case expireTime = "expire_time"
                case useFlag = "use_flag"
            }
        }
    }
    //获取我的优惠券列表
    static func getUsercouponArray(
        page:Int,
        page_size:Int,
        success: @escaping (CouponList?) -> (),
        failure: @escaping (Message) -> ()) {
        
        let paramter = [
            "page":page,
            "page_size":page_size
        ]
        
        Base<CouponList>.request(URIString: "user/get_coupon_list", parameters: paramter, success: { (data) in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    struct UnpayRecard : Codable {
        let list: [Info]
        struct Info: Codable {
            let receipt_sn : String
            let money : String
            let reason : String
            let pay_status : Int
            let created_at : String
        }
    }

    //获取我的欠款列表
    static func fetchUserDebtInfo(
        page:Int,
        page_size:Int,
        payStatus:Int,
        success: @escaping (UnpayRecard?) -> (),
        failure: @escaping (Message) -> ()) {
        
        let paramter = [
            "page":page,
            "page_size":page_size,
            "pay_status":payStatus,
            ]
        
        Base<UnpayRecard>.request(URIString: "user/query_receipt_list", parameters: paramter, success: { (data) in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    
    struct falseDriveInfo : Codable {
        let list: [DriveInfo]
        struct DriveInfo: Codable {
            let handle_flag : Int
            let occ_time : Int
            let fine : String
            let score : Int
            let address : String
            let reason : String
            let plate_number : String
            let app_car_type_name : String
        }
    }
    
    //获取我的违章列表
    static func fetchUserWrongDriveInfo(
        page:Int,
        page_size:Int,
        handle_flag:Int,
        success: @escaping (falseDriveInfo?) -> (),
        failure: @escaping (Message) -> ()) {
        
        let paramter = [
            "page":page,
            "page_size":page_size,
            "handle_flag":handle_flag,
        ]
        
        Base<falseDriveInfo>.request(URIString: "user/get_violation", parameters: paramter, success: { (data) in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    
    //退押金
    static func outUserDeposit(type: Int,
                               success: @escaping () -> (),
                               failure: @escaping (Message) -> ()) {
        
        Base<String>.request(URIString: "user/return_deposit", parameters: ["deposit_type":type], success: { data in
            success()
        }) { error, data in
            failure(error)
        }
    }
    
    struct orderInfo : Codable {
        
        let status : Int
        let imagePath : String
        let addTime : Int
        let plateNumber : String
        let carTypeName : String
        let payMethod : Int
        let money : String
        let totalMoney : String
        let drivingDistance : Int?
        let drivingDuration : Int?
        let discountMoney : String
        let debtMoney : String?
        let drivingPath : [[Double]]?
        let appealFlag: Int?
        let orderSn: String?
        let balanceFlag: Int?
        let balanceMoney: String?
        
        enum CodingKeys: String, CodingKey {
            case status = "status"
            case imagePath = "image_path"
            case addTime = "add_time"
            case plateNumber = "plate_number"
            case carTypeName = "car_type_name"
            case payMethod = "pay_method"
            case money = "money"
            case totalMoney = "total_money"
            case drivingDistance = "driving_distance"
            case drivingDuration = "driving_duration"
            case discountMoney = "discount_money"
            case debtMoney = "debt_money"
            case drivingPath = "driving_path"
            case appealFlag = "appeal_flag"
            case orderSn = "order_sn"
            case balanceFlag = "balance_flag"
            case balanceMoney = "balance_money"
        }
    }
    
    //已完成订单详情  分时
    static func getOrderDetailInfo(
        orderId: String,
        success: @escaping (orderInfo?) -> (),
        failure: @escaping (Message) -> ()) {
        Base<orderInfo>.request(URIString: "user/get_order_detail", parameters: ["order_id":orderId], success: { data in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    
    //是否需要支付
    enum IsNeedPay: Int, Codable {
        case unNeedPay = 0
        case needPay = 1
        case refund = 2
    }
    
    //支付状态
    enum PayStatus: Int, Codable {
        case unFinish = 1 //未结清
        case finish = 2   //已结清
    }
    
    struct OrderDetailDayInfo: Codable {
        let orderId: String
        let isNeedPay: User.IsNeedPay
        let payStatus: PayStatus
        let payableAmount: String
        let beginTime: Int
        let endTime: Int
        let isOilPay: User.IsNeedPay
        let totalAmountData: TotalAmountData
        let paidAmountData: PaidAmountData
        let orderSn: String
        let imagePath: String
        let plateNumber: String
        let carTypeName: String
        
        enum CodingKeys: String, CodingKey {
            case orderId = "order_id"
            case isNeedPay = "is_need_pay"
            case payStatus = "pay_status"
            case payableAmount = "payable_amount"
            case beginTime = "begin_time"
            case endTime = "end_time"
            case isOilPay = "is_oil_pay"
            case totalAmountData = "total_amount_data"
            case paidAmountData = "paid_amount_data"
            case orderSn = "order_sn"
            case imagePath = "image_path"
            case plateNumber = "plate_number"
            case carTypeName = "car_type_name"
        }
        
        struct TotalAmountData: Codable {
            let realRentDays: String
            let totalAmount: String
            let rentAmount: String
            let noDeductibles: String
            let prepareAmount: String
            let returnAmount: String
            let oilAmount: String
            
            enum CodingKeys: String, CodingKey {
                case realRentDays = "real_rent_days"
                case totalAmount = "total_amount"
                case rentAmount = "rent_amount"
                case noDeductibles = "no_deductibles"
                case prepareAmount = "prepare_amount"
                case returnAmount = "return_amount"
                case oilAmount = "oil_amount"
            }
        }
        
        struct PaidAmountData: Codable {
            let rentDays: Int
            let prepayAmount: String
            let rentAmount: String
            let prepareAmount: String
            let noDeductibles: String
            
            enum CodingKeys: String, CodingKey {
                case rentDays = "rent_days"
                case prepayAmount = "prepay_amount"
                case rentAmount = "rent_amount"
                case prepareAmount = "prepare_amount"
                case noDeductibles = "no_deductibles"
            }
        }
    }

    //已完成订单详情  日租
    static func getOrderDetailForDayInfo(
        orderId: String,
        success: @escaping (OrderDetailDayInfo?) -> (),
        failure: @escaping (Message) -> ()) {
        Base<OrderDetailDayInfo>.request(URIString: "user/query_daily_order_detail", parameters: ["order_id":orderId], success: { data in
            success(data)
        }) { error, data in
            failure(error)
        }
    }

    struct Guarantee : Codable {
        let certPhotoFlag: Int
        let trafficImagePath: String
        let commerceImagePath: String
        let license1ImagePath: String
        let license2ImagePath: String
        
        enum CodingKeys: String, CodingKey {
            case certPhotoFlag = "cert_photo_flag"
            case trafficImagePath = "traffic_image_path"
            case commerceImagePath = "commerce_image_path"
            case license1ImagePath = "license_1_image_path"
            case license2ImagePath = "license_2_image_path"
        }
    }
    
    //查看保单照片和行驶证照片
    static func certificate(
        orderId: String,
        success: @escaping (Guarantee?) -> (),
        failure: @escaping (Message) -> ()) {
        
        Base<Guarantee>.request(URIString: "user/query_car_cert_image", parameters: ["order_id":orderId], success: { data in
            success(data)
        }) { error, data in
            failure(error)
        }
    }

    struct VersionInfo: Codable {
        let versionSn: String
        let forceFlag: Int
        let addTime: Int
        let downLoadurl: String
        let versionNote: String
        
        enum CodingKeys : String, CodingKey {
            case versionSn = "version_sn"
            case forceFlag = "force_flag"
            case addTime = "add_time"
            case downLoadurl = "download_url"
            case versionNote = "version_note"
        }
    }

    //版本更新
    static func versions(
        success: @escaping (VersionInfo?) -> (),
        failure: @escaping (Message) -> ()) {
        Base<VersionInfo>.request(URIString: "detection_version", parameters: ["app_client":"user"], success: { versionInfo in
            success(versionInfo)
        }) { (message, versionInfo) in
            failure(message)
        }
    }

    //申诉订单
    static func UserComplainOrder(
        orderId: String,
        complain_type: Int,
        complain_content: String,
        complain_money: String,
        success: @escaping (Bool?) -> (),
        failure: @escaping (Message) -> ()) {
        
        let paramter = [
            "order_id":orderId,
            "complain_type":complain_type,
            "complain_content":complain_content,
            "complain_money":complain_money
            ] as [String : Any]
        
        Base<String>.request(URIString: "user/parking_appeal", parameters: paramter, success: { (status) in
            success(true)
        }) { (message, data) in
            failure(message)
        }
    }
    
    struct BalanceDetail: Codable {
        
        struct Item: Codable {
            let useType: String
            let money: String
            let createdAt: String
            let moneyType: Int
            
            enum CodingKeys : String, CodingKey {
                case useType = "use_type"
                case money = "money"
                case createdAt = "created_at"
                case moneyType = "money_type"
            }
        }
        
        let list: [Item]
        let page: String
        let pageSize: String
        let recordCount: Int
        
        enum CodingKeys : String, CodingKey {
            case list = "list"
            case page = "page"
            case pageSize = "page_size"
            case recordCount = "record_count"
        }
    }
    
    /// 查询用户余额明细
    ///
    /// - Parameters:
    ///   - page: 当前页码
    ///   - pageSize: 每页条数
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func balanceDetail(page: Int,
                              pageSize: Int,
                              success: @escaping (BalanceDetail?) -> (),
                              failure: @escaping (Message) -> ()) {
        
        let parameters: [String: Any] = ["page": page, "page_size": pageSize]
        
        Base<BalanceDetail>.request(URIString: "user/query_balance_detail", parameters: parameters, success: { data in
            success(data)
        }) { (message, data) in
            failure(message)
        }
    }
    
    struct CardList: Codable {
        let list:[CardInfo]
        struct CardInfo: Codable {
            let bankName: String
            let imagePath: String
            let creditNumber: String?
            enum CodingKeys: String, CodingKey {
                case bankName = "bank_name"
                case imagePath = "image_path"
                case creditNumber = "credit_number"
            }
        }
    }
    
    /// 已绑定信用卡列表
    ///
    /// - Parameters:
    ///   - flag: 查找标识
    ///   - payFlag: 支持快钱 1：否，2是
    ///   - returnFlag: 支持退款 1：否，2是
    ///   - success:
    ///   - failure:
    static func makeBoundedCardList(
        flag: String,
        payFlag: Int? = nil,
        returnFlag: Int? = nil,
        success:@escaping (CardList?) ->(),
        failure:@escaping (Message)->()) {
        
        var parameters: [String: Any] = ["flag": flag]
        
        if let value = payFlag {
            parameters["kqpay_flag"] = value
        }
        
        if let value = returnFlag {
            parameters["return_flag"] = value
        }
        
        Base<CardList>.request(URIString: "user/get_bank_list", parameters: parameters, success: { data in
            success(data)
        }) { (message, data) in
            failure(message)
        }
    }
    
    struct BankInfo: Codable {
        let bankId: String
        let bankName: String
        let bankIcon: String
        let userName: String
        let identifyNumber: String
        
        enum CodingKeys: String, CodingKey {
            case bankId = "bank_id"
            case bankName = "bank_name"
            case bankIcon = "bank_icon"
            case userName = "user_name"
            case identifyNumber = "identify_card"
        }
    }
    
    ///根据信用卡号获取银行信息
    ///
    /// - Parameters:
    ///   - bankCardId: 银行卡
    ///   - success:
    ///   - failure:
    static func banckDetailInfo(
        bankCardId: String,
        success: @escaping (BankInfo?) ->(),
        failure: @escaping (Message) -> ()) {
        
        let parameters: [String: Any] = ["credit_number": bankCardId]
        
        Base<BankInfo>.request(URIString: "user/get_bank_info", parameters: parameters, success: { data in
            success(data)
        }) { (message, data) in
            failure(message)
        }
    }
    
    /// 绑卡发送短信验证码
    ///
    /// - Parameters:
    ///   - creditNumber: 银行卡号(16位
    ///   - safeCode: 安全码（3位）
    ///   - expireTime: 有效期
    ///   - telephone: 手机号
    ///   - success:
    ///   - failure:
    static func boundCardSendCode(
        creditNumber: String,
        safeCode: String,
        expireTime: String,
        telephone: String,
        success: @escaping () ->(),
        failure: @escaping (Message) -> ()) {
        
        let parameters: [String: Any] = ["credit_number": creditNumber,
                                         "safe_code":safeCode,
                                         "expire_time":expireTime,
                                         "telephone":telephone]
        
        Base<String>.request(URIString: "user/bind_send_check_code", parameters: parameters, success: { data in
            success()
        }) { (message, data) in
            failure(message)
        }
    }
    
    /// 绑定信用卡
    ///
    /// - Parameters:
    ///   - bankId: 银行卡id
    ///   - creditNumber: 银行卡号(16位）
    ///   - safeCode: 安全码（3位）
    ///   - expireTime: 有效期
    ///   - telephone: 手机号
    ///   - checkCode: 验证码
    ///   - success:
    ///   - failure:
    static func boundingCard(
        bankId: String,
        creditNumber: String,
        safeCode: String,
        expireTime: String,
        telephone: String,
        checkCode: String,
        success: @escaping () ->(),
        failure: @escaping (Message) -> ()) {
        
        let parameters: [String: Any] = ["bank_id": bankId,
                                         "credit_number":creditNumber,
                                         "safe_code":safeCode,
                                         "expire_time":expireTime,
                                         "telephone":telephone,
                                         "check_code": checkCode]
        
        Base<String>.request(URIString: "user/bind_bank", parameters: parameters, success: { data in
            success()
        }) { (message, data) in
            failure(message)
        }
    }
    
    /// 保存银行卡信息
    ///
    /// - Parameters:
    ///   - type: 押金类型（1：基础；2：日租）
    ///   - cardNumber: 银行卡号
    ///   - bankId: 银行ID
    ///   - openBank: openBank description开户行
    ///   - success:
    ///   - failure:
    static func saveCardInfo(type: Int,
                      cardNumber: String,
                      bankId: String,
                      openBank: String,
                      success: @escaping () ->(),
                      failure: @escaping (Message) -> ()) {
        
        let parameters: [String: Any] = ["deposit_type": type,
                                         "card_no":cardNumber,
                                         "bank_id":bankId,
                                         "open_bank":openBank]
        
        Base<String>.request(URIString: "user/save_bank_card_info", parameters: parameters, success: { data in
            success()
        }) { (message, data) in
            failure(message)
        }
    }
    
    //我的行程  模型
    struct QuaryList:Codable {
        let list : [Item]
        //一个行程订单模型
        struct Item: Codable{
            let dayCouponName : String
            let useEndTime : Int
            let couponPrice : String
            let eventSn : String
            let status : Int
            
            enum CodingKeys: String, CodingKey {
                case dayCouponName = "day_coupon_name"
                case useEndTime = "use_end_time"
                case couponPrice = "coupon_price"
                case eventSn = "event_sn"
                case status = "status"
            }
        }
    }
    
    /// 获取日租预售券列表
    ///
    /// - Parameters:
    ///   - page: 页数
    ///   - success:
    ///   - failure:
    static func fetchQuaryList(page: Int,
                               success: @escaping ([QuaryList.Item]?) -> (),
                               failure: @escaping (Message) -> ()) {
        
        let parameters = ["page": page]
        
        Base<QuaryList>.request(URIString: "user/query_day_coupon_list", parameters: parameters, success: { data in
            success(data?.list)
        }) { error, data in
            failure(error)
        }
    }
    
    /// 驳回认证详情
    struct RejectDetail: Codable {
        let rejectReason: String
        let rejectOptionList: [RejectInfo]
        struct RejectInfo: Codable{
            let rejectOptionImage : String
            let rejectOption : Int
            
            enum CodingKeys: String, CodingKey {
                case rejectOptionImage = "reject_option_image"
                case rejectOption = "reject_option"
            }
        }
        enum CodingKeys: String, CodingKey {
            case rejectReason = "reject_reason"
            case rejectOptionList = "reject_option_list"
        }
    }

    /// 认证驳回详情
    ///
    /// - Parameters:
    ///   - success: 成功
    ///   - failure: 失败
    static func rejectAttestation(success: @escaping (RejectDetail?) -> (),
                               failure: @escaping (Message) -> ()) {
        Base<RejectDetail>.request(URIString: "user/audit_reject_detail", success: { data in
            success(data)
        }) { error, data in
            failure(error)
        }
    }
    
    /// 重新提交驳回
    ///
    /// - Parameters:
    ///   - success: 成功
    ///   - failure: 失败
    static func commitReject(rejectInfo:[[String: Any]], success: @escaping () -> (),
                                  failure: @escaping (Message) -> ()) {
        var a = [String: [String: Any]]()
        for (i, v) in rejectInfo.enumerated() {
            a["reject_option_list[\(i)]"] = v
        }
        Base<String>.request(URIString: "user/audit_submit",parameters: a, success: { data in
            success()
        }) { error, data in
            failure(error)
        }
    }
    
    //上传文件
    static func uploadFile(_ image: UIImage, success: @escaping (String)->()) {
        DispatchQueue.global().async {
            let imgData = image.compress(maxSizeKBytes: kMaxSizeKBytes)
            DispatchQueue.main.async {
                XHProgressHUD.showStatusInfo("上传中...")
                let file = HTTPRequest.File(data: imgData, name: "image_path", fileName: "file.jpg", mimeType: "image/jpg")
                File.upload(file: file, success: { data in
                    
                    XHProgressHUD.dismiss()
                    XHProgressHUD.showSuccess("上传成功")
                    
                    if let path = data?.imagePath {
                        success(path)
                    } else {
                        XHProgressHUD.showError("上传异常")
                    }
                }) { error in
                    XHProgressHUD.dismiss()
                    XHProgressHUD.showError(error.msg)
                }
            }
        }
    }
}
